<template>
    <div class="nav">
        <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item :to="{ path: '/control' }">商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>菜品详情</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <!-- 搜索 -->
    <div class="search">
        <h3>筛选条件</h3>
        <div class="search-details">
            <el-button type="danger" size="small" @click="delproduct(ids)">全部清除</el-button>
            <label>
                <span>搜索</span>
                <el-input placeholder="请输入产品名" clearable size="small" v-model="search.name"  />
            </label>
            <label>
                <span>分类搜索</span>
                <el-select placeholder="请选择分类" size="small" clearable v-model="search.category">
                    <el-option v-for="item in catelist" :key="item.id" :label="item.title" :value="item.id" />
                </el-select>
            </label>
            <el-button size="small" @click="add('add')">新增</el-button>

        </div>
    </div>
    <!-- 内容 -->
    <div class="container">
        <el-config-provider :locale="zhCn">
            <!-- 当选择项发生改变时触发，有一个参数会返回所有勾选的数据 -->
            <el-table :data="pagesData" style="width: 100%" max-height="500px" @selection-change="changeId">
                <el-table-column type="selection" width="55" v-model="ids" />
                <el-table-column fixed prop="name" label="菜品名称" width="100" />
                <el-table-column fixed prop="old_price" label="菜品原价" width="80" />
                <el-table-column fixed prop="price" label="菜品价格" width="80" />
                <el-table-column fixed prop="image" label="图片" width="100">
                    <template #default="scope">
                        <img :src="scope.row.image" alt="" style="width: 50px;height: 50px;">
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="描述信息" width="200" />
                <el-table-column prop="category_id" label="菜品分类" width="100" />
                <el-table-column prop="sales" label="菜品销量" width="80" />
                <el-table-column prop="net_content" label="净含量" width="80" />
                <el-table-column prop="quality" label="保质期" width="100" />
                <el-table-column prop="storage_conditions" label="存储条件" width="100" />
                <el-table-column prop="production" label="生产地" width="100" />
                <el-table-column prop="status" label="是否起售" width="100" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="add('edit', scope.row)">修改</el-button>
                        <el-button type="danger" size="small" @click="delproduct([scope.row.id])">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </el-config-provider>
    </div>
    <!-- 分页 -->
    <div class="page">
        <el-config-provider :locale="zhCn">
            <el-pagination v-model:current-page="pages.current" :page-sizes="[4, 6, 8]"
                layout="total,sizes,prev, pager, next" :total="pages.pagetotal" v-model:page-size='pages.pagesize' />
        </el-config-provider>
    </div>
    <!-- 弹出的页面 -->
    <el-dialog v-model="visible" width="800px" @close="close()">
        <template #header>
            <div class="my-header">
                <h4>{{ filte === 'add' ? '新增菜品信息' : '修改菜品信息' }}</h4>
                <el-form :rules="rules" :model="info" ref="formrules" label-width="100px" :inline="true">
                    <el-form-item label="菜品名称" prop="name">
                        <el-input placeholder="请输入菜品名" clearable v-model="info.name" size="small" class="inp">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="菜品原价" prop="old_price">
                        <el-input-number v-model="info.old_price" :min="0" :max="100" @change="handleChange" />
                    </el-form-item>
                    <el-form-item label="菜品描述" prop="description">
                        <el-input v-model="info.description" placeholder="请输入菜品描述" clearable size="small" type="textarea"
                            class="inp">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="菜品价格" prop="price">
                        <el-input-number v-model="info.price" :min="0" :max="100" @change="handleChange" />
                    </el-form-item>

                    <el-form-item label="菜品类型" prop="category_id">
                        <el-select placeholder="请选择分类" size="small" clearable v-model="info.category_id" class="inp">
                            <el-option v-for="item in catelist" :key="item.id" :label="item.title " :value="item.id" />
                        </el-select>
                    </el-form-item>
                        
                    <el-form-item label="菜品销量" prop="sales">
                        <el-input v-model="info.sales" placeholder="请输入菜品销量" clearable size="small" class="inp">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="净含量" prop="net_content">
                        <el-input v-model="info.net_content" placeholder="请输入菜品净含量" clearable size="small" class="inp">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="保质期" prop="quality">
                        <el-input v-model="info.quality" placeholder="请输入菜品保质期" clearable size="small" class="inp">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="存储方式" prop="storage_conditions">
                        <el-input v-model="info.storage_conditions" placeholder="请输入菜品存储方式" clearable size="small"
                            class="inp">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="生产地" prop="production">
                        <el-input v-model="info.production" placeholder="请输入菜品生产地" clearable size="small" class="inp">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="是否起售" prop="status">
                        <el-switch v-model="info.status" />
                    </el-form-item><br>
                    <el-form-item label="产品图片" prop="image">
                        <el-upload class="avatar-uploader"
                            action="#"
                            ref = "file"
                            :limit="1"
                            :http-request="uploadImg"
                            :on-change="ChangeUpdate"
                            :before-upload="beforeAvatarUpload"
                            >
                            <img class="avatar" :src="info.image" v-if="info.image"/>
                            <svg>
                                <use xlink:href="#icon-enlarge"></use>
                            </svg>

                        </el-upload>
                    </el-form-item>
                    <div style="text-align: center;"> <el-button type="success"
                            @click="changeProduct(formrules)">提交</el-button></div>

                </el-form>
            </div>
        </template>
    </el-dialog>
</template> 
<script setup>

import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import http from '../tools/axios';
// 分类数据
const catelist = ref([
    { id: 1, title: '新品尝鲜' },
    { id: 2, title: '精选套餐' },
    { id: 3, title: '特色锅底' },
    { id: 4, title: '精品涮肉' },
    { id: 5, title: '火锅丸滑' },
    { id: 6, title: '调料蘸料' },
    { id: 7, title: '川渝特色' },
])
// 产品详情数据
const product = ref([
    {
        id: 1, name: '青虾滑1', price: '18.9', category_id: 1,
        image: 'https://tse2-mm.cn.bing.net/th/id/OIP-C.v2RCDRg3fnr3H5ofDn2E1QHaKB?w=115&h=180&c=7&r=0&o=5&category_id=1.7',
        description: '口感弹韧，爽滑，鲜甜', sales: '999+', net_content: '100g', quality: '12个月', storage_conditions: '冷冻', production: '中国', status: '1'
    },
    {
        id: 2, name: '青虾滑2', price: '18.9', category_id: 2,
        image: 'https://ts2.cn.mm.bing.net/th?id=OIP-C.v2RCDRg3fnr3H5ofDn2E1QHaKB&w=214&h=290&c=8&rs=1&qlt=90&o=6&category_id=3.1&rm=2',
        description: '口感弹韧，爽滑，鲜甜', sales: '999+', net_content: '100g', quality: '12个月', storage_conditions: '冷冻', production: '中国', status: '1'
    },
    {
        id: 3, name: '青虾滑3', price: '18.9', category_id: 1,
        image: 'https://ts2.cn.mm.bing.net/th?id=OIP-C.v2RCDRg3fnr3H5ofDn2E1QHaKB&w=214&h=290&c=8&rs=1&qlt=90&o=6&category_id=3.1&rm=2',
        description: '口感弹韧，爽滑，鲜甜', sales: '999+', net_content: '100g', quality: '12个月', storage_conditions: '冷冻', production: '中国', status: '1'
    },
    {
        id: 4, name: '青虾滑4', price: '18.9', category_id: 2,
        image: 'https://ts2.cn.mm.bing.net/th?id=OIP-C.v2RCDRg3fnr3H5ofDn2E1QHaKB&w=214&h=290&c=8&rs=1&qlt=90&o=6&category_id=3.1&rm=2',
        description: '口感弹韧，爽滑，鲜甜', sales: '999+', net_content: '100g', quality: '12个月', storage_conditions: '冷冻', production: '中国', status: '1'
    },
])

// 查询菜品接口
const getDate = () => {
    http.get('/product/inquire').then((res) => {
        console.log(res.data);
        product.value = res.data.data
    })
}
const getlist = () => {
    http.get('/product/catelist').then((res) => {
        console.log(res.data);
        catelist.value = res.data.data
    })
}

getlist()
getDate()



// 搜索数据
const search = ref({
    name: '',
    category: ''
})

const ids = ref([])
const changeId = (value) => {
    ids.value = value.map(item => {
        return item.id
    })
}
// 搜索事件 函数写法
// const Sdata = ref([])
// const searchData = ()=>{
//     Sdata.value = product.value.filter(item=>{
//         console.log('**'+item);
//         return item.name.includes(search.value.name)
//     })
// }
// searchData()

//计算属性写法 在页面加载完成时会加载一次
// const searchData = computed(()=>{
//     return product.value.filter(item=>{
//         return item.name.includes(search.value.name)&&
//         (search.value.category ? item.category_id === search.value.category : true)
//     })
// })

const searchData = computed(() => {
    console.log(product.value);
    let arr = product.value.filter(item => {
        return item.name.includes(search.value.name) &&
            (search.value.category ? item.category_id === search.value.category : true)
    })

    // JSON.parse(JSON.stringify(arr))防止原对象受到污染
    return JSON.parse(JSON.stringify(arr)).map(item => {
        for (var i = 0; i < catelist.value.length; i++) {
            if (catelist.value[i].id === item.category_id) {
                item.category_id = catelist.value[i].title
            }
        }
        return item
    })
})
// 页码数据
const pages = ref(
    { current: 1, pagesize: 4, pagetotal: searchData.value.length }
)

// 分页功能
const pagesData = computed(() => {
    pages.value.pagetotal = searchData.value.length;
    const start = (pages.value.current - 1) * pages.value.pagesize;
    const end = pages.value.current * pages.value.pagesize;
    console.log(start, end);
    return searchData.value.slice(start, end)
})


// 删除事件 删除事件接口
 // product.value=product.value.filter(item=>{
    //     if(item.id !== id){
    //         return item
    //     }
    // })
    // 多选删除
    // product.value = product.value.filter(item=>{
    //     return !id.includes(item.id)
    // })
const delproduct = (id) => {
   
    if (confirm('你确定要删除吗？')) {
        http.post('/product/delete', { ids: id }).then((res) => {
            console.log(res.data);
        })
    }
    getDate()
}




// 弹窗功能
const visible = ref(false)
const info = ref({})

const rules = ref({
    name: [
        { required: true, message: '请输入菜品名', trigger: 'blur' },

    ],
    price: [
        { required: true, message: '请输入菜品价格', trigger: 'blur' },

    ],
    old_price: [
        { required: true, message: '请输入菜品价格', trigger: 'blur' },

    ],
    category_id: [
        { required: true, message: '请输入菜品类型', trigger: 'blur' },

    ],
    description: [
        { required: true, message: '请输入菜品描述', trigger: 'blur' },

    ],
    sales: [
        { required: true, message: '请输入菜品销量', trigger: 'blur' },

    ],
    net_content: [
        { required: true, message: '请输入菜品净含量', trigger: 'blur' },

    ],
    quality: [
        { required: true, message: '请输入菜品保质期', trigger: 'blur' },

    ],
    storage_conditions: [
        { required: true, message: '请输入菜品存储方式', trigger: 'blur' },

    ],
    production: [
        { required: true, message: '请输入菜品生产地', trigger: 'blur' },

    ],

})

const router = useRouter()

// 表单提交
const formrules = ref(null)
const filte = ref('add')
// 新增事件
const add = (str, obj) => {
    visible.value = true;
    filte.value = str
    // 防止数据粘连
    if (obj) info.value = { ...obj }
}
const file = ref()
// 关闭弹窗 清除表单数据
const close = () => {
// clearFiles 清除上传文件
    file.value.clearFiles()
    info.value = {}
}
// 修改和添加
const changeProduct = (formEl) => {

    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            if (info.value.status === true) info.value.status = 1
                else info.value.status = 0
               
            
            if (filte.value === 'add') {

                http.post('/product/add', info.value).then(res => {
                    ElMessage({
                        showClose: true,
                        message: '添加成功',
                        type: 'success',
                    })
                })
                //     info.value.id = new Date().getTime()
                // if(info.value.status === true) info.value.status = 1
                // else info.value.status = 0
                // product.value.unshift(info.value)
                //     ElMessage({
                //         showClose: true,
                //         message: '添加成功',
                //         type: 'success',
                //     })
            } else {
               catelist.value.map(item=>{
                if(item.title == info.value.category_id){
                    info.value.category_id = item.id
                }
                return item
               })
                http.post('/product/update', info.value).then(res => {
                    ElMessage({
                        showClose: true,
                        message: '修改成功',
                        type: 'success',
                    })
                })
            }
            getDate()
            visible.value = false
        } else {
            ElMessage({
                showClose: true,
                message: '请补全信息重新添加',
                type: 'warning',
            })
        }
    })
}

// 图片上传事件
const beforeAvatarUpload=(rawFile)=>{
    const format = rawFile.type.split('/').pop().toLowerCase();
    console.log(rawFile);
    let isIMG = ['png','jpg','webp','jpeg','svg']
    if(!isIMG.includes(format)){
        return ElMessage({
            showClose: true,
            message: '上传图片只能是 png、jpg、webp、jpeg、svg 格式!',
            type: 'warning',
        })
    }
    if(rawFile.size>1024*1024*20){
        return ElMessage({
            showClose: true,
            message: '上传图片大小不能超过 20MB!',
            type: 'warning',
        })
    }
}

// 上传文件改变的时候
const ChangeUpdate = (UploaFild,UploaFilds) => {
    file.value.clearFiles()
}
// 图片上传
const uploadImg = (option) => {
    // 定义一个图片上传文件
    let formData = new FormData()
    formData.append("image",option.file)
    http.post('/upload/upload',formData).then(res=>{
        console.log(res.data.data);
        info.value.image = res.data.data.path
    })
}

</script>

<style scoped>
.search {
    margin-top: 20px;
}

.search-details {
    display: flex;
}

.search-details label {
    margin-left: 30px;
    color: #999;
}

.container {
    margin: 30px;
    margin-top: 50px;
}

label .el-input,
label .el-select {
    margin-left: 10px;
    width: 200px;
}

label .el-select {
    margin-right: 30px;
}

.page {
    display: flex;
    justify-content: center;
}

.inp {
    width: 200px;
}
.el-upload img {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>